from django.shortcuts import render, render_to_response
from django.http import JsonResponse
from django.http.response import HttpResponse, HttpResponseRedirect
from django.contrib.auth.decorators import login_required
import json
import os

from oms import settings
from api.salt_api import SaltAPI
from assets.models import Asset


@login_required()
def remote_exec(request):
    """
    远程执行命令
    :param request: 
    :return: 
    """
    header_title, sub_title, path1, path2 = "", "", "任务平台", "远程执行"

    ret = '111'
    tgtcheck = ''
    danger = {'rm', 'reboot', 'init', 'shudown'}
    if request.method == 'POST':
        action = request.get_full_path().split('=')[1]
        if action == 'exec':
            tgt = request.POST.get('tgt')
            fun = 'cmd.run'
            arg = request.POST.get('arg')
            tgtcheck = Asset.objects.filter(hostname=tgt)
            argcheck = arg not in danger
            if tgtcheck and argcheck:
                salt_api = SaltAPI(apiurl=settings.SALT_API['apiurl'], username=settings.SALT_API['user'],
                                   password=settings.SALT_API['password'])
                ret = salt_api.remote_execution(tgt, fun, arg)
            elif not tgtcheck:
                ret = '目标主机不正确，请重新输入'
            elif not argcheck:
                ret = '尝试执行危险命令'
        data = {'ret': ret}
        return JsonResponse(data)
        # return render_to_response('salt_remote_exec.html', {'ret': ret, 'tgt': tgt, 'arg': arg})
    else:
        return render(request, 'jobs/remote_exec.html', locals())


@login_required()
def fast_execute_script(request):
    """
    快速脚本执行
    :param request: 
    :return: 
    """
    header_title, sub_title, path1, path2 = "", "", "任务平台", "快速脚本执行"
    if request.method == 'POST':
        pass
    else:
        return render(request, 'jobs/fast_execute_script.html', locals())


@login_required()
def fast_push_file(request):
    """
    快速分发文件
    :param request: 
    :return: 
    """
    header_title, sub_title, path1, path2 = "", "", "任务平台", "快速分发文件"
    if request.method == 'POST':
        pass
    else:
        return render(request, 'jobs/fast_push_file.html', locals())


@login_required()
def job_list(request):
    """
    常用作业执行
    :param request: 
    :return: 
    """
    header_title, sub_title, path1, path2 = "", "", "任务平台", "常用作业执行"
    if request.method == 'POST':
        pass
    else:
        return render(request, 'jobs/job_list.html', locals())


@login_required()
def new_task(request):
    """
    新建作业
    :param request: 
    :return: 
    """
    header_title, sub_title, path1, path2 = "", "", "任务平台", "新建作业"
    if request.method == 'POST':
        pass
    else:
        return render(request, 'jobs/new_task.html', locals())


@login_required()
def crontab_task_list(request):
    """
    定时作业
    :param request: 
    :return: 
    """
    header_title, sub_title, path1, path2 = "", "", "任务平台", "定时作业"
    if request.method == 'POST':
        pass
    else:
        return render(request, 'jobs/crontab_task_list.html', locals())


@login_required()
def task_instance_list(request):
    """
    执行历史
    :param request: 
    :return: 
    """
    header_title, sub_title, path1, path2 = "", "", "任务平台", "执行历史"
    if request.method == 'POST':
        pass
    else:
        return render(request, 'jobs/task_instance_list.html', locals())


@login_required()
def chosen_server(request):
    return render(request, 'jobs/chosen_server.html', locals())


@login_required()
def new_crontab_task(request):
    return render(request, 'jobs/new_crontab_task.html', locals())


def upload_demo(request):
    if request.method == 'POST':
        # f = request.FILES.get('files')
        # print(f)
        files = request.FILES.getlist('files')
        if not files:
            return HttpResponse('not files for upload!')
        for file in files:
            # print(file)
            # print(type(file))
            # print(file.name)
            # print(file.size)
            # destination = open(os.path.join('/tmp', file.name), 'wb+')
            with open(os.path.join('/tmp', file.name), 'wb+') as destination:
                for chunk in file.chunks():
                    destination.write(chunk)
            destination.close()
            # return json.dumps({"files": [{"name": file.name, "minetype": 'pdf'}]})
            ret = {"files": [{"name": file.name, "minetype": 'dd'}]}
            return HttpResponse(json.dumps(ret))
            # return HttpResponse('upload over!')
    else:
        return render(request, 'jobs/upload_demo.html', locals())
